package com.xi.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xi.mapper.UserMapper;
import com.xi.pojo.*;
import com.xi.service.LogService;
import com.xi.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogService logService;

    /*
     * 用户登录
     * */
    @Override
    public Log login(User user) {
        // 获取数据库中的用户名密码
        User userLogin = userMapper.getUsernameAndPassword(user);

        //设置用户的id


        //获取登录日志进行返回
        Log log = new Log();

        //设置为用户登录
        log.setRole(0);
        log.setOperatingTime(LocalDateTime.now());
        log.setStatus(userLogin != null ? 1 : 0);

        //进行登录日志信息添加
        logService.addLog(log);
        return log;
    }

    @Override
    public PageResult page(UserQueryParam userQueryParam) {
        // 1.设置分页参数
        PageHelper.startPage(userQueryParam.getPage(), userQueryParam.getPageSize());

        // 2.执行查询
        List<User> rows = userMapper.list(userQueryParam);

        // 3.解析查询结果，并封装
        Page<User> p = (Page<User>) rows;
        return new PageResult<>(p.getTotal(), p.getResult());
    }

    /*
    * 根据id删除用户
    * */
    @Override
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }

    /*
    * 获取总用户数
    * */
    @Override
    public Integer count() {
        return userMapper.count();
    }

    @Override
    public PageResult<Book> page(UserBookQueryParam userBookQueryParam) {
        PageHelper.startPage(userBookQueryParam.getPageNum(), userBookQueryParam.getPageSize());
        List<Book> userlist = userMapper.searchBookByParams(userBookQueryParam);
        Page<Book> p = (Page<Book>) userlist;
        return new PageResult<>(p.getTotal(),p.getResult());
    }

    @Override
    public void addUser(User user) {
        user.setRegisterTime(LocalDateTime.now());
        user.setReviseTime(LocalDateTime.now());

        userMapper.addUser(user);
    }
    // 新增：检查用户名是否存在
    public boolean checkUserExists(String username) {
        User existingUser = userMapper.getUserByUsername(username);
        return existingUser != null;
    }

    @Override
    public User getCurrentUser(String username) {
        return userMapper.getUserByUsername(username);
    }

    @Override
    public List<Borrowable> searchBorrowBook() {
        return userMapper.searchBorrowBook();
    }

    @Override
    public boolean borrowBook(Integer userId, Integer bookId) {
        try {
            Book book = userMapper.getBookById(bookId);
            if (book == null || book.getStock() <= 0) {
                return false;
            }

            // 获取系统配置
            SystemConfig config = userMapper.getSystemConfig();
            int borrowDays = config != null ? config.getRenewalDays() : 14; // 默认14天

            Borrow borrow = new Borrow();
            borrow.setUserId(userId);
            borrow.setBookId(bookId);
            borrow.setBorrowingTime(LocalDateTime.now());
            borrow.setReturnTime(LocalDateTime.now().plusDays(borrowDays));
            borrow.setStatus(1);
            borrow.setBorrowDays(borrowDays); // 设置 borrow_days 字段

            userMapper.addBorrow(borrow);

            userMapper.updateBookStock(bookId, book.getStock() - 1);

            return true;
        } catch (Exception e) {
            log.error("借阅图书失败", e);
            return false;
        }
    }


    @Override
    public List<Borrowable> searchBorrowBookByUserId(Integer userId) {
        return userMapper.searchBorrowBookByUserId(userId);
    }

    @Override
    public boolean returnBook(Integer userId, Integer bookId) {
        try {
            // 查询当前借阅记录
            Borrow borrow = userMapper.getBorrowRecord(userId, bookId);
            if (borrow == null || borrow.getStatus() != 1) {
                return false; // 没有找到借阅记录或已归还
            }

            // 设置为已归还
            borrow.setStatus(0);

            // 更新借阅记录
            userMapper.updateBorrowStatus(borrow);

            // 增加图书库存
            Book book = userMapper.getBookById(bookId);
            if (book != null) {
                userMapper.updateBookStock(bookId, book.getStock() + 1);
            }

            return true;
        } catch (Exception e) {
            log.error("归还图书失败", e);
            return false;
        }
    }

    @Override
    public boolean renewBook(Integer userId, Integer bookId) {
        try {
            // 查询当前借阅记录
            Borrow borrow = userMapper.getBorrowRecord(userId, bookId);
            if (borrow == null || borrow.getStatus() != 1) {
                return false; // 没有找到借阅记录或已归还
            }

            // 续借：延长7天
            borrow.setReturnTime(borrow.getReturnTime().plusDays(7));

            // 更新借阅记录
            userMapper.updateBorrowStatus(borrow);

            return true;
        } catch (Exception e) {
            log.error("续借图书失败", e);
            return false;
        }
    }

    @Override
    public boolean reserveBook(Integer userId, Integer bookId, String username) {
        try {
            // 检查是否已预约过该书
            Reservation existing = userMapper.getExistingReservation(userId, bookId);
            if (existing != null) {
                return false; // 已预约
            }

            // 获取书籍信息
            Book book = userMapper.getBookById(bookId);
            if (book == null || book.getStock() > 0) {
                return false; // 库存不为0或书不存在
            }

            // 构造预约记录
            Reservation reservation = new Reservation();
            reservation.setUserId(userId);
            reservation.setBookId(bookId);
            reservation.setBookTitle(book.getTitle());
            reservation.setBookIsbn(""); // 如果没有 ISBN 字段，可设为空或占位符
            reservation.setUserName(username);

            // 插入预约记录
            userMapper.addReservation(reservation);
            return true;
        } catch (Exception e) {
            log.error("预约失败", e);
            return false;
        }
    }

    @Override
    public List<Reservation> getReservationsByUserId(Integer userId) {
        return userMapper.getReservationsByUserId(userId);
    }

    @Override
    public boolean cancelReservation(Integer reservationId) {
        try {
            int rowsAffected = userMapper.deleteReservationById(reservationId);
            return rowsAffected > 0;
        } catch (Exception e) {
            log.error("取消预约失败", e);
            return false;
        }
    }

    @Override
    public boolean updateUserInfo(User user) {
        int rows = userMapper.updateUserInfo(user);
        return rows > 0;
    }

    @Override
    public boolean updateUserInfo(String oldUsername, String newUsername, String realName, String phone) {
        int rows = userMapper.updateUserInfo(oldUsername, newUsername, realName, phone);
        return rows > 0;
    }

    @Override
    public boolean changePassword(String username, String oldPassword, String newPassword) {
        // 验证旧密码
        User user = userMapper.getUserByUsername(username);
        if (user == null || !user.getPassword().equals(oldPassword)) {
            return false;
        }

        // 更新密码
        int rows = userMapper.changePassword(username, newPassword);
        return rows > 0;
    }

    @Override
    public Borrow getBorrowRecord(Integer userId, Integer bookId) {
        return userMapper.getBorrowRecord(userId, bookId);
    }


}
